﻿using Common.Interfaces;

namespace Common.Models;

/// <summary>
/// 结果响应
/// </summary>
/// <typeparam name="T"></typeparam>
public class Result : IResult
{
    internal Result()
    {
    }
    internal Result(bool success, IEnumerable<string> errors)
    {
        Success = success;
        Message = string.Join(";", errors);
    }
    /// <summary>
    /// 是否成功
    /// </summary>
    public bool Success { get; init; }
    /// <summary>
    /// 状态码
    /// </summary>
    public int Code { get; set; } = 200;

    /// <summary>
    /// 提示消息
    /// </summary>
    public string Message { get; set; } = "操作成功";
    public static Result Succeed()
    {
        return new Result(true, new string[] { "操作成功" });
    }
    public static Task<Result> SucceedAsync()
    {
        return Task.FromResult(new Result(true, new string[] { "操作成功" }));
    }
    public static Result Failure(IEnumerable<string> errors)
    {
        return new Result(false, errors);
    }
    public static Task<Result> FailureAsync(IEnumerable<string> errors)
    {
        return Task.FromResult(new Result(false, errors));
    }
}


/// <summary>
/// 结果响应
/// </summary>
/// <typeparam name="T">泛型结果</typeparam>
public class Result<T> : Result, IResult<T>
{
    /// <summary>
    /// 返回数据
    /// </summary>
    public T? Data { get; set; }

    public static new Result<T> Failure(IEnumerable<string> errors)
    {
        return new Result<T> { Success = false, Message = string.Join(";", errors) };
    }
    public static new async Task<Result<T>> FailureAsync(IEnumerable<string> errors)
    {
        return await Task.FromResult(Failure(errors));
    }
    public static Result<T> Succeed(T data)
    {
        return new Result<T> { Success = true, Data = data };
    }
    public static Result<T> Succeed(bool success, T data, IEnumerable<string> errors)
    {
        if (success)
        {
            return new Result<T> { Success = true, Data = data, Message = string.Join(";", errors) };
        }
        else
        {
            return Failure(errors);
        }
    }
    public static async Task<Result<T>> SucceedAsync(T data)
    {
        return await Task.FromResult(Succeed(data));
    }
    public static async Task<Result<T>> SucceedAsync(bool success, T data, IEnumerable<string> errors)
    {
        if (success)
            return await Task.FromResult(Succeed(data));
        else
            return await Task.FromResult(Failure(errors));
    }
}
